package listener;

import domain.SysUser;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import java.util.ArrayList;
import java.util.List;

@WebListener
public class OnlineUserListener implements HttpSessionAttributeListener {
    @Override
    public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
        HttpSession session = httpSessionBindingEvent.getSession();
        ServletContext context = session.getServletContext();
        List<SysUser> userList =null;

        if (session.getAttribute("User") != null){
            SysUser user = (SysUser) session.getAttribute("User");
            if (context.getAttribute("UserList") == null){
                userList = new ArrayList<>();
                userList.add(user);
                context.setAttribute("UserList",userList);
            }else {
                userList= (List<SysUser>) context.getAttribute("UserList");
                userList.add(user);
                context.setAttribute("UserList",userList);
            }

        }
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {

    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {

    }
}
